﻿using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using Yz.Base;

namespace Yz.FileService.Middlewares
{
    public class ThumbnailMiddleware : BaseUploadMiddleware, IMiddleware
    {
        public Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            if (context.Request.Query.ContainsKey("w") || context.Request.Query.ContainsKey("h"))
            {
                var ext = Path.GetExtension(context.Request.Path);
                //不能处理缩略图
                if (!FileTypeList.ImgList.Contains(ext))//不是图片
                {
                    return next.Invoke(context);
                }
                var w = int.Parse(context.Request.Query["w"].FirstOrDefault() ?? "0");
                var h = int.Parse(context.Request.Query["h"].FirstOrDefault() ?? "0");

                var filePath = context.Request.Path.Value.Replace(_uploadConfig.VirtualPath, _uploadConfig.PhysicalPath);
                var addStr = "." + w + "_" + h + ext;
                var newPath = filePath + addStr;
                ////修改路径
                context.Request.Path = context.Request.Path + addStr;
                context.Request.QueryString = new QueryString("");
                //缩略图存在
                if (File.Exists(newPath))
                {
                    return next.Invoke(context);
                }
                //源文件不存在
                if (!File.Exists(filePath))
                {
                    context.Response.StatusCode = 404;
                    return Task.CompletedTask;
                }
                using (FileStream fs = File.OpenRead(filePath))
                {
                    Image image = Image.Load(fs);
                    image.Mutate(a => a.Resize(w, h));
                    image.Save(newPath);
                    fs.Flush();
                }
                return next.Invoke(context);
            }
            else
            {
                return next.Invoke(context);
            }
        }
    }
}
